User defined function - can you make it immutable?

by: whitingke, 7 years ago


Hello fellow Pythonistas!

I realise that user defined functions are mutable, which means if I choose to run In [4] twice the returned value updates so if the first time round I got 1000.94844269,  1000.69324339],
       [ 1000.9212632 ,  1000.13607887], if I run it again I get 2000.948 and so on. If I then need to do something else with that slice the chain is affected further down.

Here is my code.
[
In [2] def find_slice():
    find_slice = mat[:2, 1:3]
    return (find_slice)


find_slice ()

In [3] def get_matrix():
    return np.array(
      [[ 0.35066314,  0.94844269,  0.69324339,  0.32790416],
       [ 0.7935923 ,  0.9212632 ,  0.13607887,  0.56358399],
       [ 0.25597054,  0.74834666,  0.81322464,  0.11280075],
       [ 0.53822742,  0.63970183,  0.1439784 ,  0.58045905]])

mat = get_matrix()

In [4] def update_slice():
        matx = mat[:2, 1:3]
        matx += 1000
        return(matx)

update_slice ()

]

My question is: How is the memory pointer working in this case? How could I re-write the code to ensure that there are no mutable values. Really I would like to understand the behaviour of my current code, not just have a solution :)

I did videos here regarding function and looked in my Learn Python book but didn't find any answers. Is there any book I should read that would help with this?

Thanks for the fishing rod!

Kind regards,

Kai



You must be logged in to post. Please login or register an account.